﻿using System;
using System.Collections.Generic;
//using System.Linq;
//using System.Text;
using TreeNode = System.Windows.Forms.TreeNode;
using TreeNodeCollection = System.Windows.Forms.TreeNodeCollection;
using AMS.DeDuplicator.CommonLayer.Adapter;
//using AMS.DeDuplicator.CommonLayer;

namespace AMS.DeDuplicator.CommonLayer.Iterator
{
    public class TreeIterator : IIterator<ISelectableText>
    {
        Stack<TreeNode> _nodeStack;

        public TreeIterator(ITree tree, NodeIterationOption option)
        {
            InputValidator.ValidateNotNull(tree);

            _nodeStack = new Stack<TreeNode>();
            PopulateStack(tree, option);
        }

        private void PopulateStack(ITree tree, NodeIterationOption option)
        {
            foreach (TreeNode node in tree.Nodes)
            {
                if (option != NodeIterationOption.NonRootNodes)
                    _nodeStack.Push(node);

                if (option != NodeIterationOption.RootNodes)
                    PopulateStack(node.Nodes);
            }
        }

        private void PopulateStack(TreeNodeCollection nodes)
        {
            // throw all Nodes on the stack
            foreach (TreeNode node in nodes)
            {
                _nodeStack.Push(node);

                PopulateStack(node.Nodes);
            }
        }

        public bool HasNext()
        {
            // check Stack for next node
            return _nodeStack.Count > 0;
        }

        public ISelectableText GetNext()
        {
            if (!HasNext())
                throw new ArgumentOutOfRangeException("iterator does not have next");

            return new TreeNodeAdapter(_nodeStack.Pop());
        }

        public enum NodeIterationOption
        {
            AllNodes,
            RootNodes,
            NonRootNodes
        }
    }
}
